# # 设置项目名称
# project(web_frontend)
SET(PROJ_NAME web_frontend)

# 检查BUILD_WEB变量是否已定义
if(NOT DEFINED BUILD_WEB)
    # 如果BUILD_WEB未定义（独立构建时），则默认设置为ON
    set(BUILD_WEB ON)
endif()

# 只有当 BUILD_WEB 选项为 ON 时才构建 web 前端
if(BUILD_WEB)
    # 查找Node.js可执行文件
    find_program(NODE_EXECUTABLE NAMES node nodejs)
    if(NOT NODE_EXECUTABLE)
        message(FATAL_ERROR "Node.js not found!")
    endif()

    # 查找npm可执行文件
    find_program(NPM_EXECUTABLE NAMES npm)
    if(NOT NPM_EXECUTABLE)
        message(FATAL_ERROR "npm not found!")
    endif()

    # 确保PROJECT_SOURCE_DIR已定义，用于输出目录
    if(NOT DEFINED PROJECT_SOURCE_DIR)
        # 如果未定义（独立构建时），使用当前目录的上两级
        get_filename_component(PROJECT_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../.." ABSOLUTE)
    endif()

    # 定义自定义目标来构建Vue项目
    add_custom_target(
        web_build ALL
        COMMAND ${NPM_EXECUTABLE} install --prefer-offline --no-audit
        COMMAND ${CMAKE_COMMAND} -E env NODE_OPTIONS=--max-old-space-size=4096 ${NPM_EXECUTABLE} run build
        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
        COMMENT "Building Vue.js project"
        BYPRODUCTS ${CMAKE_CURRENT_SOURCE_DIR}/dist
    )

    # 实现增量构建，只在源文件比目标文件新时执行构建
    file(GLOB_RECURSE WEB_SOURCE_FILES 
        ${CMAKE_CURRENT_SOURCE_DIR}/src/**/*.js
        ${CMAKE_CURRENT_SOURCE_DIR}/src/**/*.vue
        ${CMAKE_CURRENT_SOURCE_DIR}/src/**/*.json
        ${CMAKE_CURRENT_SOURCE_DIR}/package.json
    )
    set_property(
        TARGET web_build
        PROPERTY DEPENDS ${WEB_SOURCE_FILES}
    )

    # 将构建后的文件复制到out/web目录
    add_custom_command(
        TARGET web_build
        POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E make_directory ${PROJECT_SOURCE_DIR}/out/web
        COMMAND ${CMAKE_COMMAND} -E copy_directory
        ${CMAKE_CURRENT_SOURCE_DIR}/dist
        ${PROJECT_SOURCE_DIR}/out/web
        COMMENT "Copying built files to ${PROJECT_SOURCE_DIR}/out/web"
    )
else()
    message(STATUS "Web frontend build is disabled")
endif()